package com.jiaai.cloud.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.jiaai.cloud.user.entity.User;

import com.jiaai.cloud.user.service.UserService;
import com.jiaai.cloud.utils.Oauth2Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.oauth2.provider.OAuth2Authentication;

import org.springframework.web.bind.annotation.*;


import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 佳爱网络科技
 * @since 2017-07-27
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/create")
    public Object createUser(@RequestBody User user){
        userService.create(user);
        return user;
    }
    @GetMapping("/info")
    public  Object  getUserInfo(String token){
        OAuth2Authentication oAuth2Authentication = Oauth2Utils.getAuthenticationInOauth2Server(token);
        Collection <GrantedAuthority> authorities  = oAuth2Authentication.getAuthorities();
        String roles="";

        for(GrantedAuthority grantedAuthority:authorities){
            roles+=grantedAuthority.getAuthority()+",";
        }


        User user=userService.getUserByNameAndRole(oAuth2Authentication.getName(),roles);

        return  JSONObject.toJSON(user);
    }


}